package com.example.library.studentfragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.library.LoginActivity;
import com.example.library.R;
import com.example.library.util.LocalStorageManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.imageview.ShapeableImageView;

public class StudentProfileFragment extends Fragment {
    private ShapeableImageView ivAvatar;
    private TextView tvNickname;
    private LocalStorageManager localStorageManager;
    private ActivityResultLauncher<Intent> galleryLauncher;
    private ActivityResultLauncher<Intent> cameraLauncher;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        localStorageManager = new LocalStorageManager(requireContext());

        // 注册图片选择结果处理
        galleryLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == getActivity().RESULT_OK && result.getData() != null) {
                    Uri imageUri = result.getData().getData();
                    ivAvatar.setImageURI(imageUri);
                    // TODO: 保存头像到本地或上传到服务器
                }
            }
        );

        // 注册相机拍照结果处理
        cameraLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == getActivity().RESULT_OK) {
                    // TODO: 处理相机返回的图片
                }
            }
        );
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.student_profile, container, false);

        // 初始化视图
        ivAvatar = view.findViewById(R.id.ivAvatar);
        tvNickname = view.findViewById(R.id.tvNickname);
        ImageButton btnEditAvatar = view.findViewById(R.id.btnEditAvatar);
        ImageButton btnEditNickname = view.findViewById(R.id.btnEditNickname);
        View layoutChangePassword = view.findViewById(R.id.layoutChangePassword);
        View layoutAbout = view.findViewById(R.id.layoutAbout);
        MaterialButton btnLogout = view.findViewById(R.id.btnLogout);

        // 设置用户信息
        String nickname = localStorageManager.getNickname();
        tvNickname.setText(nickname != null ? nickname : "默认昵称");

        // 头像编辑点击事件
        btnEditAvatar.setOnClickListener(v -> showImagePickerDialog());

        // 昵称编辑点击事件
        btnEditNickname.setOnClickListener(v -> showNicknameEditDialog());

        // 修改密码点击事件
        layoutChangePassword.setOnClickListener(v -> {
            // TODO: 实现修改密码功能
            Toast.makeText(requireContext(), "修改密码功能开发中", Toast.LENGTH_SHORT).show();
        });

        // 关于我们点击事件
        layoutAbout.setOnClickListener(v -> {
            new MaterialAlertDialogBuilder(requireContext())
                .setTitle("关于我们")
                .setMessage("书巢图书馆座位预约系统\n版本 1.0.0")
                .setPositiveButton("确定", null)
                .show();
        });

        // 退出登录点击事件
        btnLogout.setOnClickListener(v -> {
            new MaterialAlertDialogBuilder(requireContext())
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    localStorageManager.clearUserData();
                    startActivity(new Intent(requireContext(), LoginActivity.class));
                    requireActivity().finish();
                })
                .setNegativeButton("取消", null)
                .show();
        });

        return view;
    }

    private void showImagePickerDialog() {
        String[] options = {"从相册选择", "拍照"};
        new AlertDialog.Builder(requireContext())
            .setTitle("选择头像")
            .setItems(options, (dialog, which) -> {
                if (which == 0) {
                    // 从相册选择
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    galleryLauncher.launch(intent);
                } else {
                    // 拍照
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraLauncher.launch(intent);
                }
            })
            .show();
    }

    private void showNicknameEditDialog() {
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_edit_nickname, null);
        EditText etNickname = dialogView.findViewById(R.id.etNickname);
        etNickname.setText(tvNickname.getText());
        etNickname.setSelection(etNickname.length()); // 将光标移到文本末尾

        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("修改昵称")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String newNickname = etNickname.getText().toString().trim();
                if (newNickname.isEmpty()) {
                    Toast.makeText(requireContext(), "昵称不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 保存新昵称
                localStorageManager.saveUserData(localStorageManager.getUserId(), newNickname);
                tvNickname.setText(newNickname);
                Toast.makeText(requireContext(), "昵称修改成功", Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }
} 